package com.erp.activity

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.os.Environment
import android.os.Parcelable
import android.provider.MediaStore
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.AdapterView
import android.widget.BaseAdapter
import android.widget.LinearLayout
import androidx.appcompat.app.AlertDialog
import com.erp.Interface.OnUserDataInterface
import com.erp.R
import com.erp.bean.ProdyctionClientBean
import com.erp.permission.PermissionListener
import com.erp.util.Dialogutil
import com.erp.util.Httputil
import com.erp.util.Myutil
import com.erp.util.PermissionUtils
import kotlinx.android.synthetic.main.activity_wt_photo.*
import kotlinx.android.synthetic.main.header_knoya1.*
import kotlinx.android.synthetic.main.vp_iv_photo_item1.view.*
import org.xutils.x
import java.io.File


class WtPhotoActivity : BaseActivity(), AdapterView.OnItemClickListener, AdapterView.OnItemLongClickListener, View.OnClickListener {

    private var mwidth: Int = 0
    lateinit var listphoto: MutableList<String>
    lateinit var listcid: MutableList<ProdyctionClientBean.guimingxi>
    lateinit var adapter: GvPhotoAdapter
    private var oid: String = ""
    private val a = "WtPhotoActivity"
    lateinit var updatedialog: AlertDialog
    var code = 0
    private var xuan: Int = 0
    override fun getLayoutId(): Int {
        activityname = a
        return R.layout.activity_wt_photo
    }

    override fun initCreate() {
        tv_header_title.text = "质量问题拍照"
        iv_header_left.visibility = View.VISIBLE
        tv_header_right.visibility = View.VISIBLE
        tv_header_right.text = "确定上传"
        mwidth = sp.getInt("width", 0)
        oid = intent.getStringExtra("oid")
        code = intent.getIntExtra("code", code)
        listphoto = ArrayList()
        listcid = ArrayList<ProdyctionClientBean.guimingxi>()
        adapter = GvPhotoAdapter(this, listphoto, listcid, mwidth, code)
        GvPhoto.adapter = adapter
        GvPhoto.onItemClickListener = this
        GvPhoto.onItemLongClickListener = this
        if (code == 1) {
            tv_header_title.text = "质量问题拍照"
        } else if (code == 2) {
            tv_header_title.text = "订单内容拍照"
        } else if (code == 3) {
            tv_header_title.text = "上传安装照片"
        } else if (code == 4) {
            tv_header_title.text = "上传专卖店照片"
        } else if(code == 5){
            tv_header_title.text = "上传安装照片"
            PermissionUtils.isphoto(this@WtPhotoActivity, object : PermissionListener {
                override fun onSucceed(requestCode: Int, grantPermissions: List<String>) {
                    Myutil.photo(this@WtPhotoActivity, null, 2)
                }

                override fun onFailed(requestCode: Int, deniedPermissions: List<String>) {
                    Myutil.MyTost("没有权限，无法拍照")
                }
            })
        }
        iv_header_left.setOnClickListener(this)
        tv_header_right.setOnClickListener(this)
        Log.d("onClick","code="+code)
    }

    override fun onClick(v: View) {
        when (v) {
            iv_header_left -> finish()
            tv_header_right -> if (listphoto.size > 0) {
                Log.d("onClick","code="+code)
                updatedialog = Myutil.showupdatedialog(this@WtPhotoActivity, "正在上传", false)
                Httputil.getShangchuanPhoto(code, this@WtPhotoActivity, listphoto, listcid, oid, object : OnUserDataInterface {
                    override fun onUserData(data: String) {
                        updatedialog.dismiss()
                        Myutil.MyTost("上传成功")
                        when(code){
                            5 -> {
                                val intent = Intent(this@WtPhotoActivity, DanjuWTKActivity::class.java)
                                intent.putExtra("code", 3)
                                intent.putExtra("oid",  oid)
                                startActivity(intent)
                            }
                            else -> {
                                val intent = Intent()
                                intent.putExtra("SC", true)
                                setResult(Activity.RESULT_OK, intent)
                            }
                        }
                        val file = File(Environment.getExternalStorageDirectory().toString() + "/erp/photo")
                        Myutil.deleteLfile(file)
                        finish()
                    }

                    override fun onNot(throwable: String) {
                        updatedialog.dismiss()
                        Log.d("TAAAG", "onNot=$throwable")
                    }
                })
            } else {
                Myutil.MyTost("没有照片")
            }
        }
    }

    override fun onItemClick(parent: AdapterView<*>, view: View, position: Int, id: Long) {
        if (position == listphoto.size) {
            PermissionUtils.isphoto(this@WtPhotoActivity, object : PermissionListener {
                override fun onSucceed(requestCode: Int, grantPermissions: List<String>) {

                        Dialogutil.photodialog2(this@WtPhotoActivity, null)

                }

                override fun onFailed(requestCode: Int, deniedPermissions: List<String>) {
                    Myutil.MyTost("没有权限，无法拍照")
                }
            })
        } else {
            val intent = Intent(this@WtPhotoActivity, DanjianivActivity::class.java)
            intent.putExtra("url", listphoto[position])
            if (code == 1) {
                intent.putExtra("code", 2)
                try {
                    intent.putExtra("id", Integer.valueOf(listcid[position].id))
                } catch (e: NumberFormatException) {
                    intent.putExtra("id", -1)
                }

            } else {
                intent.putExtra("code", 1)
            }
            startActivityForResult(intent, 101)
            xuan = position
        }
    }

    public override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (data == null) {
            return
        }
        when (requestCode) {
            98 ->{
                if (resultCode == Activity.RESULT_OK) {
                    val name = data.getStringExtra("PATH")
                    if (code == 1) {
                        listcid.add(data.getParcelableExtra<Parcelable>("cid") as ProdyctionClientBean.guimingxi)
                    }
                    listphoto.add(name)
                    adapter.notifyDataSetChanged()
                }else{
                    Myutil.photo(this@WtPhotoActivity,null,2)
                }

            }
            99 -> {

                val selectedImage = data.data
                val filePathColumns = arrayOf(MediaStore.Images.Media.DATA)
                if(selectedImage != null){
                    val c = contentResolver.query(selectedImage, filePathColumns, null, null, null)
                    c!!.moveToFirst()
                    val columnIndex = c.getColumnIndex(filePathColumns[0])
                    val imagePath = c.getString(columnIndex)
                    var intent = Intent(this@WtPhotoActivity, DanjianivActivity::class.java)
                    intent.putExtra("url",imagePath);
                    if (code ==2 || code == 3 || code == 4) {
                        intent.putExtra("code",1);
                    } else {
                        intent.putExtra("code",2);
        //                    Myutil.photo(this@WtPhotoActivity, null, 2)
                    }
        //                intent.putExtra("code",code);
                    startActivityForResult(intent,98);
                }
            }
            100 -> if (resultCode == Activity.RESULT_OK) {
                //                    x.image().bind(ivDanju, name);
                val name = data.getStringExtra("dir")
                if (code == 1) {
                    listcid.add(data.getParcelableExtra<Parcelable>("cid") as ProdyctionClientBean.guimingxi)
                }
                listphoto.add(name)
                adapter.notifyDataSetChanged()
            }
            101 -> {
                if (code == 1) {
                    listcid.removeAt(xuan)
                    listcid.add(xuan, data.getParcelableExtra<Parcelable>("cid") as ProdyctionClientBean.guimingxi)
                }
                adapter.notifyDataSetChanged()
            }
        }
    }

    override fun onItemLongClick(parent: AdapterView<*>, view: View, position: Int, id: Long): Boolean {
        if(position < listphoto.size){
            val dialog = AlertDialog.Builder(this@WtPhotoActivity)
            dialog.setTitle("提示")
            dialog.setMessage("要删除这张照片吗？")
            dialog.setNegativeButton("确定") { dialog, which ->
                listphoto.removeAt(position)
                adapter.notifyDataSetChanged()
            }
            dialog.setPositiveButton("取消") { dialog, which -> dialog.dismiss() }
            dialog.show()
        }
        return true
    }


    class GvPhotoAdapter(var mcontext: Context, var listphoto: List<String>, var listcid: List<ProdyctionClientBean.guimingxi>, val mwidth: Int, val code: Int) : BaseAdapter() {
        var munflater: LayoutInflater = LayoutInflater.from(mcontext)

        override fun getCount(): Int {
            return listphoto.size + 1
        }

        override fun getItem(position: Int): Any {
            return listphoto[position]
        }

        override fun getItemId(position: Int): Long {
            return position.toLong()
        }

        override fun getView(position: Int, convertView: View?, parent: ViewGroup): View {
            var v: View
            var h: ViewHolder
            if (convertView == null) {
                v = munflater.inflate(R.layout.vp_iv_photo_item1, null)
                h = ViewHolder(v)
                v.tag = h
            } else {
                v = convertView
                h = convertView.tag as ViewHolder
            }
            val linearParams = h.edit_ll.layoutParams as LinearLayout.LayoutParams
            // 取控件aaa当前的布局参数
            linearParams.height = mwidth / 3 // 当控件的高强制设成365象素
            h.edit_ll.layoutParams = linearParams // 使设置好的布局参数应用到控件aaa
            if (position < listphoto.size) {
                x.image().bind(h.iv_item, listphoto[position])
                if (code == 1) {
                    Myutil.settv(listcid[position].guihao, h.tv_GuiHao)
                    Myutil.settv(listcid[position].name, h.tv_GuiMing)
                }
            } else {
                h.iv_item.setImageResource(R.mipmap.erp_photo)
                h.ll_tv.visibility = View.GONE
            }

            return v
        }

        class ViewHolder(var v: View) {
            val edit_ll = v.edit_ll
            val tv_GuiHao = v.tv_GuiHao
            val tv_GuiMing = v.tv_GuiMing
            val ll_tv = v.ll_tv
            val iv_item = v.iv_item
        }
    }

}
